package cn.kgc.itrip.service.impl;

import cn.kgc.itrip.common.DtoUtil;
import cn.kgc.itrip.common.ErrorCode;
import cn.kgc.itrip.common.MD5;
import cn.kgc.itrip.common.RedisUtils;
import cn.kgc.itrip.dto.Dto;
import cn.kgc.itrip.dto.ItripUserVO;
import cn.kgc.itrip.mapper.userEmail.UserEmailMapper;
import cn.kgc.itrip.pojo.ItripUser;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.regex.Pattern;

@Service
public class UserPhoneServiceImpl implements UserPhoneService{


    @Resource
    private UserEmailMapper userEmailMapper;

    @Resource
    private RedisUtils redisUtils;

    @Resource
    private UserPhoneSendService userPhoneSendService;

    /**
     * 手机注册
     * @param itripUserVO
     * @return
     */
    @Override
    public Dto doLoginPhone(ItripUserVO itripUserVO) throws Exception{
        //补充判断手机格式，是否正确
        if (!validPhone(itripUserVO.getUserCode())){
            return DtoUtil.returnFail("用户已存在", ErrorCode.AUTH_USER_ALREADY_EXISTS);
        }
        //1.判断，该手机用户是否存在
        ItripUser user = userEmailMapper.findUser(itripUserVO.getUserCode());
        if (user == null){
            //2.创造手机验证码
            String md5 = MD5.getMd5(new Date().toLocaleString(), 6);
            //3.在redis中保存手机验证码
            redisUtils.setExpire(itripUserVO.getUserCode(),md5,60);
            //4.发送手机验证码
            //手机号，激活码，模板，激活码有效时间
            userPhoneSendService.sendPhoneMes(itripUserVO.getUserCode(),md5,1,1);
            //5.保存注册的手机号
            ItripUser itripUser = new ItripUser();
            itripUser.setUserCode(itripUserVO.getUserCode());
            itripUser.setUserName(itripUserVO.getUserName());
            itripUser.setUserPassword(MD5.getMd5(itripUserVO.getUserPassword(),32));
            itripUser.setCreationDate(new Date());
            itripUser.setUserType(0);
            itripUser.setActivated(0);
            userEmailMapper.userAdd(itripUser);
            //6.返回值
            return DtoUtil.returnSuccess("注册成功");
        }else {
            return DtoUtil.returnFail("手机号已存在",ErrorCode.AUTH_USER_ALREADY_EXISTS);
        }
    }


    /**
     * 手机格式验证方法
     * @param userCode
     * @return
     * @throws Exception
     */
    @Override
    public boolean validPhone(String userCode) throws Exception{
        //18261732354
        String reg = "^1[35789]{1}\\d{9}$";
        return Pattern.compile(reg).matcher(userCode).find();
    }
}
